<template>
  <div>
    <el-select
      v-model="selectValue"
      :disabled="disabled"
      :multiple="multiple"
      value-key="albumId"
      clearable
      filterable
      remote
      :remote-method="handleSearch"
      placeholder="请选择专辑"
      @change="handleChange"
      @clear="handleSearch('')"
    >
      <div
        v-infinite-scroll="load"
        :infinite-scroll-immediate="false"
        :infinite-scroll-delay="500"
        :infinite-scroll-distance="200"
        class="option"
      >
        <el-option
          v-for="item in options"
          :key="item.albumId"
          :label="item.title"
          :value="item"
        >
          <span class="option__left">{{ item.title }}</span>
          <span class="option__right">专辑ID: {{ item.albumId }}</span>
        </el-option>
      </div>
      <div class="footer-total">
        总计 {{ total }} 条，当前展示 {{ options.length }} 条
      </div>
    </el-select>
  </div>
</template>

<script>
import { getAdminAlbums } from 'dependencies/api/album'
import LoadingMixins from 'modules/mixins/section-loading'
export default {
  components: {},
  mixins: [LoadingMixins],
  props: {
    // 绑定的值（双向绑定回显的值）
    value: {
      type: [Number, String, Object],
      default() {
        return undefined
      }
    },
    data: {
      type: [Number, Object],
      default() {
        return {}
      }
    },
    multiple: {
      type: Boolean,
      default: false
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 下拉修改时使用到的参数
    editinfo: {
      type: Object,
      default: () => {}
    },
    prop: {
      type: String,
      default: ''
    },
    albumProp: {
      type: String,
      default: ''
    }
  },
  data() {
    // 这里存放数据
    return {
      options: [],
      selectValue: '',
      pageIndex: 1,
      pageSize: 30,
      total: 0,
      search: ''
    }
  },
  watch: {
    value(val, oldValue) {
      val = Number(val)
      if (this.selectValue && this.selectValue.albumId === val || !val) {
        return
      }
      const item = this.options.find(({ albumId }) => albumId === val) || {}
      this.selectValue = {
        albumId: val,
        title: item.title || ''
      }
      if (!item.title && oldValue !== undefined) {
        this.handleSearch('')
      }
    }
  },
  mounted() {
    // 函数调用顺序要在options赋值为空数组之后
    this.initData()
    this.getOptionList()
  },
  // 方法集合
  methods: {
    reset() {
      this.pageIndex = 1
      this.total = 0
      this.search = ''
      this.selectValue = {}
      this.options = []
      this.getOptionList()
    },
    handleSearch(title) {
      this.pageIndex = 1
      this.total = 0
      this.search = title
      this.options = []
      this.getOptionList()
    },
    load() {
      if (this.pageIndex < Math.ceil(this.total / this.pageSize)) {
        this.pageIndex += 1
        this.getOptionList()
      }
    },
    // 处理值改变事件
    handleChange(value) {
      if (this.prop) {
        if (typeof this.data === 'object') {
          this.$set(this.data, this.prop, value.albumId || '')
        } else {
          this.$emit('update:data', value.albumId || '')
        }
      }
    },
    // 下拉框隐藏事件
    handleVisible(val) {
      // 下拉框隐藏后重新加载下拉数据
      if (!val) {
        this.getOptionList()
      }
    },
    submit() {
      if (this.prop) {
        if (typeof this.data === 'object') {
          this.$set(this.data, this.prop, this.selectValue?.albumId || '')
        } else {
          this.$emit('update:data', this.selectValue?.albumId || '')
        }
      }
    },
    // 获取列表数据
    async getOptionList() {
      if (this.options.length && this.options.length >= this.total) return
      this.loading()
      try {
        let data = await getAdminAlbums({
          query: {
            title: this.search,
            pageSize: this.pageSize,
            pageIndex: this.pageIndex
          }
        })
        if (data.success) {
          data = data.data
          this.total = data.totalCount
          if (data.data.length) {
            this.options = this.options.concat(data.data)
            if (
              this.value &&
              data.data.find(
                i =>
                  i.albumId === this.value || String(i.albumId) === this.value
              ) === undefined
            ) {
              this.load()
            }
          }
        }
      } finally {
        this.loaded()
      }
    },
    // 初始化数据
    initData() {
      // 当父组件上存在值时，对select值进行初始化
      const value = this.value
      if (typeof value !== 'object' && !isNaN(value)) {
        this.selectValue = {
          albumId: Number(value),
          title: this.albumProp ? this.data[this.albumProp] : undefined
        }
        this.search = this.selectValue.title
        return
      }
      this.selectValue = this.value
    }
  }
}
</script>
<style lang="scss" scoped>
.option {
  height: 200px;
  overflow-y: auto;
  &__left {
    float: left;
  }
  &__right {
    float: right;
    color: #8492a6;
    font-size: 13px;
  }
}
.pagin {
  background: #fff;
}
::-webkit-scrollbar {
  width: 10px;
}
.footer-total {
  font-size: 14px;
  text-align: center;
  color: #999;
}
</style>
